/**
 * 所有实体请求都在这里进行处理
 */
var express = require("express");
var router = express.Router();
var _ = require("lodash");
var mongodb = require("../../../models/db.ts");
var ObjectID = require("mongodb").ObjectID;
const ObjectConfig = require("../../../models/ObjectConfig.ts"); //拿到总配置信息。
var systemFields = require("../../../config/system_fields.json"); //拿到系统字段。

var RoleAccess = require("../../../models/RoleAccess.ts");
const FieldType = {
  STRING: "string", //字符串类型
  NUMBER: "number", //数字类型
  DATETIME: "dateTime", //日期时间类型
  BOOLEAN: "boolean", //布尔类型
  SIMSELECT: "simple_select", //单选类型
  RELATION: "relation", //关联类型
};

/**
 * 获取该实体的所有数据
 * 如果有权限则能查到所有实体数据。
 */
//@Api(name="/rests/json/:apiKey/getAll")
router.post("/json/:apiKey/getAll", (req, res) => {
  let user = req.session.user;
  let dataBaseName = user.company.companyCap + "_service";
  let apiKey = req.params.apiKey;
  //打开数据库
  mongodb.connect((error) => {
    if (error) {
      res.send({
        code: 201,
        msg: "服务器错误，请联系管理员",
        data: null,
      });
    }
    const DataBase = mongodb.db(dataBaseName); // 获取数据库
    DataBase.collection(apiKey, function (err, collection) {
      if (err) {
        res.send({
          code: 201,
          msg: "服务器错误，请联系管理员",
          data: null,
        });
      }
      //根据 query 对象查询文章

      let role = user.role;
      if (role) {
        role = JSON.parse(role);
      }
      RoleAccess.findById(role.id, dataBaseName, (err, result) => {
        var query = {};
        if (result.access.includes(`${apiKey}_select`)) {
          collection
            .find(query)
            .sort({ updateTime: -1 })
            .toArray(function (err, all) {
              if (err) {
                res.send({
                  code: 201,
                  msg: "服务器错误，请联系管理员",
                  data: null,
                });
              } else {
                res.send({
                  code: 200,
                  msg: "查询成功",
                  data: all,
                });
              }
            });
        } else {
          res.send({
            code: 200,
            msg: "查询成功",
            data: [],
          });
        }
      });
    });
  });
});

/**
 * 获取时间戳内的实体数据信息。
 */
//@Api(name="/rests/json/:apiKey/switch/data")
router.post("/json/:apiKey/switch/data", (req, res) => {
  let user = req.session.user;
  let dataBaseName = user.company.companyCap + "_service";
  let apiKey = req.params.apiKey;
  const body = req.body;
  var startTime = body.startTime || "0";
  var endTime = body.endTime || "0";
  //打开数据库
  mongodb.connect((error) => {
    if (error) {
      res.send({
        code: 201,
        msg: "服务器错误，请联系管理员",
        data: null,
      });
    }
    const DataBase = mongodb.db(dataBaseName); // 获取数据库
    DataBase.collection(apiKey, function (err, collection) {
      if (err) {
        res.send({
          code: 201,
          msg: "服务器错误，请联系管理员",
          data: null,
        });
      }
      let role = user.role;
      if (role) {
        role = JSON.parse(role);
        RoleAccess.findById(role.id, dataBaseName, (err, result) => {
          var query = {};
          if (result.admin) {
            query = {
              updateTime: { $gte: startTime, $lte: endTime },
            };
            collection
              .find(query)
              .sort({ updateTime: -1 })
              .toArray(function (err, source) {
                if (err) {
                  res.send({
                    code: 201,
                    msg: "服务器错误，请联系管理员",
                    data: null,
                  });
                } else {
                  res.send({
                    code: 200,
                    msg: "查询成功",
                    data: source,
                  });
                }
              });
          } else {
            query = {
              updateTime: { $gte: startTime, $lte: endTime },
              user: JSON.stringify({ id: user._id, name: user.name }),
            };
            collection
              .find(query)
              .sort({ updateTime: -1 })
              .toArray(function (err, source) {
                if (err) {
                  res.send({
                    code: 201,
                    msg: "服务器错误，请联系管理员",
                    data: null,
                  });
                } else {
                  res.send({
                    code: 200,
                    msg: "查询成功",
                    data: source,
                  });
                }
              });
          }
        });
      } else {
        var query = {
          updateTime: { $gte: startTime, $lte: endTime },
          user: JSON.stringify({ id: user._id, name: user.name }),
        };
        collection
          .find(query)
          .sort({ updateTime: -1 })
          .toArray(function (err, source) {
            if (err) {
              res.send({
                code: 201,
                msg: "服务器错误，请联系管理员",
                data: null,
              });
            } else {
              res.send({
                code: 200,
                msg: "查询成功",
                data: source,
              });
            }
          });
      }
    });
  });
});

//获取某个实体的单个数据
//@Api(name="/rests/json/:apiKey/details")
router.post("/json/:apiKey/details", (req, res) => {
  let user = req.session.user;
  let dataBaseName = user.company.companyCap + "_service";
  let apiKey = req.params.apiKey;
  var id = req.body.id;
  mongodb.connect((error) => {
    if (error) {
      res.send({
        code: 201,
        msg: "服务器错误，请联系管理员",
        data: null,
      });
    }
    const DataBase = mongodb.db(dataBaseName); // 获取数据库
    DataBase.collection(apiKey, function (err, collection) {
      if (err) {
        res.send({
          code: 201,
          msg: "服务器错误，请联系管理员",
          data: null,
        });
      }
      collection.findOne({ _id: ObjectID(id) }, function (err, ob) {
        if (err) {
          res.send({
            code: 201,
            msg: "服务器错误，请联系管理员",
            data: null,
          });
        }
        res.send({
          code: 200,
          msg: "查询成功",
          data: ob,
        });
      });
    });
  });
});
//提供某个实体打开创建界面需要渲染的真实样式。
//@Api(name="/rests/json/:apiKey/open/layout")
router.get("/json/:apiKey/open/layout", (req, res) => {
  let user = req.session.user;
  let dataBaseName = user.company.companyCap + "_service";
  let apiKey = req.params.apiKey;
  ObjectConfig.findByApiKey(apiKey, dataBaseName, function (err, ob) {
    if (err) {
      res.send({
        code: 201,
        msg: "服务器错误，请联系管理员",
        data: null,
      });
    } else {
      res.send({
        code: 200,
        msg: "获取布局成功",
        data: JSON.parse(ob.state),
      });
    }
  });
});

//创建某个实体的真实数据。
//@Api(name="/rests/json/:apiKey/open/create")
router.post("/json/:apiKey/open/create", (req, res) => {
  let user = req.session.user;
  let dataBaseName = user.company.companyCap + "_service";
  let apiKey = req.params.apiKey;
  let params = req.body.params;
  try {
    _.forEach(systemFields, (item) => {
      //系统字段，先设置对应的值，
      if (!params[item.apiKey]) {
        //无值
        if (item.fieldType === "5" || item.fieldType === "6") {
          //单选或者关联类型。
          let option = item.option;
          if (option && option.length > 0) {
            params[item.apiKey] = JSON.stringify(option[0]); //设置单选第一个为默认选中项。
          } else {
            //关联类型。
            if (
              item.apiKey === "createBy" ||
              item.apiKey === "updateBy" ||
              item.apiKey === "user"
            ) {
              //输入当前登录用户信息。
              params[item.apiKey] = JSON.stringify({
                id: user._id,
                name: user.name,
              });
            }
          }
        } else if (item.fieldType === "4") {
          //日期时间类型
          params[item.apiKey] = new Date().getTime(); //获取当前时间戳
        } else if (item.fieldType === "3" || item.fieldType === "2") {
          //布尔类型 数字类型 默认值是0；
          params[item.apiKey] = 0;
        } else {
          params[item.apiKey] = ""; //字符串为空。
        }
      }
    });
    mongodb.connect((error) => {
      if (error) {
        res.send({
          code: 201,
          msg: "服务器错误，请联系管理员",
          data: null,
        });
      }
      const DataBase = mongodb.db(dataBaseName); // 获取数据库
      DataBase.collection(apiKey, function (err, collection) {
        if (err) {
          res.send({
            code: 201,
            msg: "服务器错误，请联系管理员",
            data: null,
          });
        }
        //根据 query 对象查询文章
        collection.insert(params, { safe: true }, function (err, post) {
          if (err) {
            res.send({
              code: 201,
              msg: "服务器错误，请联系管理员",
              data: null,
            });
          } else {
            res.send({
              code: 200,
              msg: "创建成功",
              data: post.ops[0],
            });
          }
        });
      });
    });
  } catch (error) {
    res.send(error);
  }
});

//更新某个实体的真实数据。
//@Api(name="/rests/json/:apiKey/open/update")
router.post("/json/:apiKey/open/update", (req, res) => {
  let user = req.session.user;
  let dataBaseName = user.company.companyCap + "_service";
  let apiKey = req.params.apiKey;
  let _id = req.body._id;
  let params = req.body.params;
  try {
    mongodb.connect((error) => {
      if (error) {
        res.send({
          code: 201,
          msg: "服务器错误，请联系管理员",
          data: null,
        });
      }
      const DataBase = mongodb.db(dataBaseName); // 获取数据库
      DataBase.collection(apiKey, function (err, collection) {
        if (err) {
          res.send({
            code: 201,
            msg: "服务器错误，请联系管理员",
            data: null,
          });
        }
        collection.updateOne(
          { _id: ObjectID(_id) },
          { $set: params },
          function (err) {
            if (err) {
              res.send({
                code: 201,
                msg: "服务器错误，请联系管理员",
                data: null,
              });
            }
            res.send({
              code: 200,
              msg: "更新成功",
              data: { ...params, _id },
            });
          }
        );
      });
    });
  } catch (error) {
    res.send(error);
  }
});

//删除某个实体数据
//@Api(name="/rests/json/:apiKey/delete")
router.post("/json/:apiKey/delete", (req, res) => {
  let user = req.session.user;
  let dataBaseName = user.company.companyCap + "_service";
  let apiKey = req.params.apiKey;
  var id = req.body.id;
  mongodb.connect((error) => {
    if (error) {
      res.send({
        code: 201,
        msg: "服务器错误，请联系管理员",
        data: null,
      });
    }
    const DataBase = mongodb.db(dataBaseName); // 获取数据库
    DataBase.collection(apiKey, function (err, collection) {
      if (err) {
        res.send({
          code: 201,
          msg: "服务器错误，请联系管理员",
          data: null,
        });
      }
      //根据 query 对象查询文章

      collection.remove({ _id: ObjectID(id) });
      res.send({
        code: 200,
        msg: "删除成功",
        data: id,
      });
    });
  });
});

//创建取值方案
function getValueByType(type, apiKey, params, value) {
  switch (type) {
    case FieldType.STRING:
      params[apiKey] = value ? `${value}` : "";
      break;
    case FieldType.NUMBER:
      params[apiKey] = value ? Number.parseInt(value) : 0;
      break;
    case FieldType.DATETIME:
      params[apiKey] = value || "";
      break;
    case FieldType.BOOLEAN:
      params[apiKey] = value ? Number.parseInt(value) : 0;
      break;
    case FieldType.SIMSELECT:
      params[apiKey] = value ? `${value}` : "";
      break;
    case FieldType.RELATION: //关联类型进行取值。
      params[apiKey] = value ? `${value}` : "";
      break;
    default:
      break;
  }
}

function getTime() {
  var date = new Date();
  //存储各种时间格式，方便以后扩展
  return {
    date: date,
    year: date.getFullYear(),
    month: date.getFullYear() + "-" + (date.getMonth() + 1),
    day:
      date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate(),
    minute:
      date.getFullYear() +
      "-" +
      (date.getMonth() + 1) +
      "-" +
      date.getDate() +
      " " +
      date.getHours() +
      ":" +
      (date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes()),
  };
}

module.exports = router;
